﻿using System;
using System.ComponentModel;
using System.Globalization;

namespace Gmantis.Controls.Extended
{
    public sealed class NullableTimeSpanConverter : TypeConverter
    {
        // Methods
        public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
        {
            if (sourceType == null)
            {
                throw new ArgumentNullException("sourceType");
            }
            if ((sourceType != typeof(string)) && !typeof(TimeSpan).IsAssignableFrom(sourceType))
            {
                return (sourceType == typeof(TimeSpan));
            }
            return true;
        }

        public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
        {
            if (value is TimeSpan)
            {
                return (TimeSpan?)value;
            }
            string str = value as string;
            if ((str != null) || (value == null))
            {
                return (!string.IsNullOrEmpty(str) ? new TimeSpan?(TimeSpan.Parse(str)) : null);
            }
            if (value == null)
            {
                throw new ArgumentNullException("value");
            }
            return base.ConvertFrom(value);
        }
    }
}
